<?php
namespace app\admin\controller;
use app\AdminBaseController;
use think\facade\Db;
use app\admin\model\MemberModel;

class Member extends AdminBaseController {

    public function index() {
        $where = array();
        $countWhere = array();
        if(isset($_GET['gid'])) {
            $where[] =['a.gid', '=', $_GET['gid']];
            $countWhere[] =['gid', '=', $_GET['gid']];
        }
        if(isset($_GET['name'])&&!empty($_GET['name'])) {
            $name = $_GET['name'];
            $where[] = ['a.name','like',"%$name%"];
            $countWhere[] = ['name','like',"%$name%"];
        }
        $page = isset($_GET['page'])?$_GET['page']:1;
        $pageSize = isset($_GET['pageSize'])?$_GET['pageSize']:10;
        $count = MemberModel::where($countWhere)->count('id');
        $list = MemberModel::field('a.*,g.name as gName')->where($where)->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->order('a.pid')->page($page,$pageSize)->select();
        
        return array(
            'count'=>$count,
            'list'=>$list
        );
    }

    public function searchList() {
        $where = array();
        if(isset($_GET['gid'])) {
            $where[] =['a.gid', '=', $_GET['gid']];
        }
        if(isset($_GET['name'])&&!empty($_GET['name'])) {
            $name = $_GET['name'];
            $where[] = ['a.name','like',"%$name%"];
        }
        $list = MemberModel::field('a.*,g.name as gName')->where($where)->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->select();
        return array(
            'list'=>$list
        );
    }

    public function add() {
        $params = array(
            'name'       =>  $_POST['name'],
            'character'  =>  $_POST['character'],
            'nickname'  =>  $_POST['nickname'],
            'sex'        =>  intval($_POST['sex']),
            'gid'        =>  intval($_POST['generation']),
            'pid'        =>  $_POST['parentId']!='null'?$_POST['parentId']:0,
            'birthday'   =>  $_POST['birthday'],
            'deadline'   =>  $_POST['deadline'],
            'merry'      =>  intval($_POST['merry']),
            'merry_type' =>  intval($_POST['merryType']),
            'spouse'     =>  $_POST['spouse'],
            'memo'       =>  $_POST['memo'],
            'addtime'    =>  time(),
            'updatetime' =>  time()
        );
        $result = MemberModel::insert($params);
        $res;
        if($result) {
            $res = array('success' => true );
        } else {
            $res = array('success' => false,'message'=>'添加失败！');
        }
        return $res;
    }

    public function edit() {
        $params = array(
            'name'       =>  $_POST['name'],
            'character'  =>  $_POST['character'],
            'nickname'  =>  $_POST['nickname'],
            'sex'        =>  intval($_POST['sex']),
            'gid'        =>  intval($_POST['generation']),
            'pid'        =>  $_POST['parentId']!='null'?$_POST['parentId']:0,
            'birthday'   =>  $_POST['birthday'],
            'deadline'   =>  $_POST['deadline'],
            'merry'      =>  intval($_POST['merry']),
            'merry_type' =>  intval($_POST['merryType']),
            'spouse'     =>  $_POST['spouse'],
            'memo'       =>  $_POST['memo'],
            'updatetime' =>  time()
        );
        $result = MemberModel::where('id',$_POST['id'])->update($params);
        $res;
        if($result) {
            $res = array('success' => true );
        } else {
            $res = array('success' => false,'message'=>'编辑失败！');
        }
        return $res;
    }


    public function del() {
        $where = array();
        if(isset($_GET['id'])) {
            $hasChild = MemberModel::where('pid','=',$_GET['id'])->find();
            if(isset($hasChild)) {
                return array('success'=>false,'confirm'=>true,'message'=>'查询到该成员具有后代，所有后代会一起被删除，是否继续？');
            } else {
                $result = MemberModel::where('id',$_GET['id'])->delete();
                if($result) {
                    return array('success'=>true,'message'=>'删除成功！');
                }
            }
        } else {
            return array('success'=>false,'message'=>'请选择要删除的成员');
        }
    }

    public function delMemberAndChild() {
        $allMember = MemberModel::field('id,pid')->order('pid')->select();
        $res = array(intval($_GET['id']));
        $this->getIds($allMember,$res);
        $result = MemberModel::where('id','in',$res)->delete();
        if($result) {
            return array(
                'success'=>true,
                'message'=>'删除成功！'
            );
        } else {
            return array(
                'success'=>false,
                'message'=>'删除失败！'
            );
        }
    }

    protected function getIds($list,&$result) {        
        foreach($list as $k=>$v) {
            if(in_array($v['pid'],$result)) {
                $result[]=$v['id'];
            }
        }
    }

    public function getAll() {
        $list = MemberModel::field('a.*,g.name as gName')->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->select();
        return $this->consistMultiDimensionArr($list,0);
    }

    public function getCount() {
        $total = MemberModel::count();
        $liveTotal = MemberModel::where('deadline','=','null')->count();
        $today = date("m-d");
        $birthtoday = MemberModel::where(array(array('birthday','like',"%$today%"),array('deadline','=','null')))->count();

        return array(
            'total'=>$total,
            'liveTotal'=>$liveTotal,
            'today'=>$birthtoday
        );
    }

    public function getTodayBirth() {
        $today = date("m-d");
        $where = array(array('a.birthday','like',"%$today%"),array('a.deadline','=','null'));
        $list = MemberModel::field('a.*,g.name as gName')->where($where)->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->order('a.gid')->select();
        return array('list'=>$list);
    }

    public function getChildren() {
        $list = MemberModel::select();
        $member = MemberModel::where('id','=',$_GET['id'])->find();
        $member['children'] = $this->consistMultiDimensionArr($list,$_GET['id']);
        return $member;
    }

    public function getFathers() {
        $list = MemberModel::field('a.*,g.name as gName')->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->select();
        $member = MemberModel::field('a.*,g.name as gName')->where('a.id','=',$_GET['id'])->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->find();
        $result =[];
        $this->getParents($list,$member['pid'],$result);
        $result = array_reverse($result);
        $result[] = $member;
        return $result;
    }

    public function getRelationship() {
        $member = MemberModel::field('a.*,g.name as gName')->where('a.id','=',$_GET['id'])->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->find();
        $member2 = MemberModel::field('a.*,g.name as gName')->where('a.id','=',$_GET['id2'])->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->find();
        $list = MemberModel::field('a.*,g.name as gName')->alias('a')->join(['yhq_generation'=>'g'],'a.gid=g.sort')->select();
        $fathers = [];
        $fathers2 = [];
        $this->getParents($list,$member['pid'],$fathers);
        $this->getParents($list,$member2['pid'],$fathers2);
        $fathers = array_reverse($fathers);
        $fathers2 = array_reverse($fathers2);
        $fathers[] = $member;
        $fathers2[] = $member2;
        $sameItems = array_intersect($fathers,$fathers2);        
        $count = count($sameItems)-1;
        $lastSameItem = $sameItems[$count];
        $lastSameItem['children'] = $this->consistMultiDimensionArr($list,$lastSameItem['id']);
        return $lastSameItem;
    }

    private function consistMultiDimensionArr($arr,$pid) {
        $result = array();
        foreach($arr as $value) {
            if($value['pid']==$pid) {
                $value['children'] = $this->consistMultiDimensionArr($arr,$value['id']);
                $result[] = $value;
            }
        }
        return $result;
    }

    private function getParents($arr,$pid,&$result) {
        foreach($arr as $value) {
            if($value['id']==$pid) {
                $result[] = $value;
                $this->getParents($arr,$value['pid'],$result);
            }
        }
        return $result;
    }
}